/*
 * Created on Sep 28, 2006
 */
package com.scalar.chiptrack.operations.distributor.actions;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Calendar;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.LabelValueBean;
import org.apache.poi.ss.usermodel.Workbook;

import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.chiptrack.utils.DateUtil;
import com.scalar.chiptrack.utils.ExcelUtils;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.commons.ExcelColumnProperties;
import com.scalar.chiptrack.operations.distributor.dao.DistributorDao;
import com.scalar.chiptrack.operations.distributor.forms.DistributorSearchForm;
import com.scalar.chiptrack.operations.packingslip.actions.SearchPackingSlipAction;
import com.scalar.chiptrack.operations.reports.dao.DataDumpReportsDAO;
import com.scalar.chiptrack.operations.reports.DataDumpReportsHelper;
import com.scalar.chiptrack.sales.dao.CustomerDAO;
import com.scalar.chiptrack.sales.dao.NewCustomerDAO;
import com.scalar.chiptrack.users.User;

/**
 * @author ravi
 */
public class DistributorSearchAction  extends ChipTrackAction
{
	public ActionForward execute (ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		HttpSession session = request.getSession();
		User user 			= (User) session.getAttribute ( SessionKeys.USER_KEY );
		HashMap<String,String> errors 		= new HashMap<String,String>();
		HashMap<String,String> info 		= new HashMap<String,String>();
		String action 		= request.getParameter( "action" );
		if ( user == null )
		{
			session.setAttribute ( SessionKeys.SOURCE_PAGE_KEY, "/distributorSalesSearch.do?" + request.getQueryString() );
			return ( mapping.findForward( "login" ) );
		}
        ArrayList distInfoList = null;
        Workbook workbook = null;
        String fileName = "";
		if( request.getAttribute( SessionKeys.INFO_MESSAGES ) != null )
		{
			info.putAll( ( HashMap ) request.getAttribute( SessionKeys.INFO_MESSAGES ) );
		}

		if( request.getAttribute( SessionKeys.ERROR_MESSAGES ) != null )
		{
			errors.putAll( ( HashMap ) request.getAttribute( SessionKeys.ERROR_MESSAGES ) );
		}
		
		DistributorSearchForm searchForm = (DistributorSearchForm) form;
		if ( action == null ){ 	action = ""; }
		
		if( "Search".equalsIgnoreCase( action ) )
		{
			// Fetch the list for the search creteria
			ArrayList list = new ArrayList();
			list = DistributorDao.loadDistributorSalesSearch( searchForm );

			if ( list != null && list.isEmpty() == false )
			{
				request.setAttribute( "searchList", list );
			}
			else
			{
				errors.put( "Could not find any results for the search creteria", null );
			}
		}
        if( "report".equalsIgnoreCase( action ) )
		{
            request.setAttribute( "distributorList", CustomerDAO.getAllDistributorNames() );
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.MONTH, -1);
            cal.set(Calendar.DAY_OF_MONTH, 1);
            searchForm.setFromDate( DateUtil.formatDate( cal.getTime(),  "MM/dd/yyyy" ) );
	        searchForm.setToDate( DateUtil.getCurrentDate() );
            return( mapping.findForward( "report" ) );
        }
        if( "excelReport".equalsIgnoreCase( action ) )
		{
            distInfoList = DistributorDao.getDistributorReport ( null, searchForm );

            if ("salesReport".equalsIgnoreCase(searchForm.getReportType()) )
            {
                fileName = "Distributor Sales Report From "+ StringUtils.formatDate(searchForm.getFromDate(), "MM/dd/yyyy", "dd-MMM-yyyy" ) + " To " +StringUtils.formatDate(searchForm.getToDate(), "MM/dd/yyyy", "dd-MMM-yyyy" ) +"_"+ DateUtil.getTimeStamp() ;
                workbook =  DataDumpReportsHelper.getWorkbook(distInfoList, "Distributor Sales Report",  searchForm.getFromDate(), searchForm.getToDate(), null );
            }
            else
            {
                fileName = "Distributor Inventory Report_"+ DateUtil.getTimeStamp() ;
                ExcelColumnProperties colProps1 = new ExcelColumnProperties("Unit Cost");
                colProps1.setCellStyle(ExcelColumnProperties.CELL_STYLE_CURRENCY_$);
                List<ExcelColumnProperties> list = new ArrayList<ExcelColumnProperties>();
                list.add(colProps1);
                workbook =  DataDumpReportsHelper.getWorkbook(distInfoList, "Distributor Inventory Report",  null, null, list );
            }

            ExcelUtils.generateExcelReport( workbook, fileName, response );

        }
		request.setAttribute( SessionKeys.INFO_MESSAGES, info );
		request.setAttribute( SessionKeys.ERROR_MESSAGES, errors );
		//request.setAttribute( "searchCustomerList", CustomerDAO.getAllCustomerNames() );
		request.setAttribute( "searchCustomerList", NewCustomerDAO.getAllCustomerNamesByCustomerTypeId( 2 ) );
		request.setAttribute( "distributorList", NewCustomerDAO.getAllDistributorNamesByUserType( null, user, false ) );
		request.setAttribute( "productList", SearchPackingSlipAction.loadManufacturingProducts () );
		request.setAttribute( "yearList", getYearList() );

		return( mapping.findForward( "success" ) );
	}
	
    private ArrayList getYearList()
    {
		int year = 2008;
		ArrayList yearList = new ArrayList();
		for ( int i = 0; i <= 15; i++)
		{
			yearList.add( new LabelValueBean( year+"", year+"" ) );
			year++;
		}
        return yearList;
    }
}
